import React, { useEffect, useState, useImperativeHandle } from 'react';
import orgCtrl from '@/ts/controller';
import { IPageTemplate } from '@/ts/core/thing/standard/page';
import FullScreenModal from '@/components/Common/fullScreen';
import { Button, Input, Tag, Dropdown } from 'antd';
import { IFile } from '@/ts/core';
import cls from './nav.module.less';
import SelectFile from './selectFile';
import { getResouces } from '@/config/location';
import { ItemDragging } from 'devextreme-react/list';
import { IPortalTemplates } from './pageTabManage';
import * as dev from 'devextreme-react';
import listNocheck from '/img/home/list-nocheck.png';
import listCheck from '/img/home/list-check.png';
import addImg from '/img/home/add.png';
import { NavigationItem } from '../types';
const { CheckableTag } = Tag;

const resource = getResouces();

const allPages: NavigationItem[] = [
  {
    key: 'workbench',
    label: '工作台',
    type: 'inner',
    backgroundImageUrl: `/img/${resource.location}/banner/workbench.png`,
    component: React.lazy(() => import('../Content/WorkBench/index')),
    tag: ['默认'],
  },
  {
    key: 'activity',
    label: '动态',
    type: 'inner',
    backgroundImageUrl: `/img/${resource.location}/banner/groupactivity.png`,
    component: React.lazy(() => import('../Content/Activity/index')),
    tag: ['默认'],
  },
];
const NavigationBar: React.FC<{
  ref: any;
  portalManage: IPortalTemplates;
  list: NavigationItem[];
  onChange: () => void;
}> = React.forwardRef((props, ref) => {
  const [configOpen, setConfigOpen] = useState(false);
  const [pages, setPages] = useState<IPageTemplate[]>([]);
  const [content, setContent] = useState<IFile[]>([]);
  const [selectType, setSelectType] = useState<boolean>(false);
  const [checkApp, setCheckApp] = useState<IFile>();
  const [tagType, setTagType] = useState<string>('1');
  const [selectedTags, setSelectedTags] = useState<string[]>(['全部']);
  const [searchValue, setSearchValue] = useState('');
  const allPageTagList = ['全部', '应用模板', '定制模板', '商城模板'];
  useImperativeHandle(ref, () => ({ showHideModal, configOpen }));

  useEffect(() => {
    setContent([orgCtrl.user, ...orgCtrl.user.companys]);
    initPage();
    setSearchValue('');
  }, [configOpen === true, selectedTags]);

  const onChangeInput = (e) => {
    const value = e.target.value ?? '';
    setSearchValue(value);
    if (value) {
      const filterList = pages.filter((item) => {
        return item.name.includes(value) || item.tags?.includes(value);
      });
      setPages(filterList);
    } else {
      initPage();
    }
  };
  const initPage = async () => {
    const data = props.portalManage?.portalTemplates ?? [];
    if (selectedTags[0] === '全部') {
      setPages(data);
    } else {
      const newPages = data.filter((item) => item.tags.includes(selectedTags[0]));
      setPages(newPages);
    }
  };
  useEffect(() => {
    setPages(props.portalManage?.newPortalTemplates ?? []);
  }, [checkApp]);
  const showHideModal = (bol: boolean) => {
    setConfigOpen(bol);
  };
  const onDelete = (item: IFile) => {
    props.portalManage.update(item.belongId, item.metadata);
    setPages(props.portalManage.newPortalTemplates);
  };
  const randCommonList = () => {
    return (
      <>
        {allPages.map((item, index) => {
          return (
            <div className={cls['list-item']} key={index}>
              <div className={cls['list-left']}>
                <img src={listNocheck} alt="" />
                <div className={cls['list-item']}>
                  <span>{item.label}</span>
                  {item?.tag?.map((item, key: number) => {
                    return (
                      <Tag key={key} color="processing" className="header-kind">
                        {item}
                      </Tag>
                    );
                  })}
                </div>
              </div>
              <div className={cls['list-right']}></div>
            </div>
          );
        })}
      </>
    );
  };
  const onReorder = React.useCallback(
    (e: { fromIndex: number; toIndex: number }) => {
      if (selectedTags[0] !== '全部') {
        return;
      }
      const fromAttr = pages.splice(e.fromIndex, 1);
      pages.splice(e.toIndex, 0, ...fromAttr);
      setPages(pages);
    },
    [pages],
  );
  const newRandList = () => {
    return (
      <>
        <dev.List
          dataSource={pages}
          height={'100%'}
          width={'100%'}
          pageLoadMode="scrollBottom"
          noDataText=""
          onItemReordered={onReorder}
          itemRender={(item) => {
            return (
              <div className={cls['list-item']}>
                <div className={cls['list-left']}>
                  <img onClick={() => onDelete(item)} src={listCheck} alt="" />
                  <div className={cls['list-item']}>
                    <span>{item.name}</span>
                    {item?.tags?.map((its: string, key: number) => {
                      return (
                        <Tag key={key} color="processing" className="header-kind">
                          {its}
                        </Tag>
                      );
                    })}
                  </div>
                </div>
                <div className={cls['list-right']}></div>
              </div>
            );
          }}>
          <ItemDragging
            data={pages}
            autoScroll
            allowReordering
            dropFeedbackMode="push"
            dragDirection="vertical"
            bindingOptions={{
              location: 'before',
            }}
          />
        </dev.List>
      </>
    );
  };
  const itemx: any = {
    items: [
      {
        key: '1',
        label: '添加应用模板',
      },
      {
        key: '5',
        label: '添加定制页面',
      },
      {
        key: '6',
        label: '添加商城页面',
      },
    ],
    onClick: async (item: any) => {
      setTagType(item.key);
      setSelectType(true);
    },
  };

  return (
    <div className={`navigationBar`}>
      {configOpen && (
        <FullScreenModal
          open={configOpen}
          title={'全部页面'}
          width={'50vw'}
          bodyHeight={'40vh'}
          onCancel={() => setConfigOpen(false)}
          footer={
            <>
              <Button
                type="default"
                onClick={() => {
                  setConfigOpen(false);
                }}>
                取消
              </Button>
              <Button
                type="primary"
                onClick={async () => {
                  // eslint-disable-next-line react/prop-types
                  await props.portalManage.save();
                  await props.onChange();
                  setConfigOpen(false);
                }}>
                保存修改
              </Button>
            </>
          }>
          <div className={cls['nav-main']}>
            <div className={cls['search-box']}>
              <Input onChange={onChangeInput} value={searchValue} placeholder="搜索" />
              <Dropdown menu={itemx} placement="bottomLeft">
                <img src={addImg} alt="" />
              </Dropdown>
            </div>
            <div className={cls['nav-tag']}>
              {allPageTagList.map((tag) => (
                <CheckableTag
                  key={tag}
                  checked={selectedTags.indexOf(tag) > -1}
                  onChange={() => setSelectedTags([tag])}>
                  {tag}
                </CheckableTag>
              ))}
            </div>
            <div className="list">
              {selectedTags[0] === '全部' && randCommonList()}
              {newRandList()}
            </div>
          </div>
        </FullScreenModal>
      )}
      {selectType && (
        <SelectFile
          tagType={tagType}
          onChange={() => {
            setSelectType(false);
          }}
          pages={pages}
          onCheck={(check: IFile | undefined) => {
            if (check) {
              props.portalManage.update(check.directory.spaceId, check.metadata);
              setCheckApp(check);
              setPages([...pages]);
            }
            setSelectType(false);
          }}
        />
      )}
    </div>
  );
});
NavigationBar.displayName = 'NavigationBar';

export default NavigationBar;
